/*
 *  Copyright:  (C) 2018 LingYun IoT System Studio
 *              All rights reserved.
 *
 *  File name:  dir.c
 *Description:  Operate directory.
 *
 *    Version:  1.1
 *     Author:  Guo Wenxue <guowenxue@gmail.com>
 *		        Copied by Zhu Tianyin <zhuty_cn@163.com>
 *  ChangeLog:  1.0  Release initial version in 2018.
 *              1.1  Copy and change some details on "01/07/2021".
 */
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

#define TEST_DIR "dirr"

int main(int argc, char **argv)
{
	int rv;
	int fd1;
	int fd2;
	DIR *dirp;
	struct dirent *direntp;

	if(mkdir(TEST_DIR, 0755)<0)
	{
		printf("Creat directory '%s' failure: %s\n", TEST_DIR, strerror(errno));
		return -1;
	}

	if(chdir(TEST_DIR)<0)
	{
		printf("Change directory to '%s' failure: %s\n", TEST_DIR, strerror(errno));
		rv = -2;
		goto cleanup;
	}

	if((fd1=creat("file1.txt", 0644))<0)
	{
		printf("Creat file1.txt failure: %s\n", strerror(errno));
		rv = -3;
		goto cleanup;
	}

	if((fd2=creat("file2.txt", 0644))<0)
	{
		printf("Creat file2.txt failure: %s\n", strerror(errno));
		rv = -4;
		goto cleanup;
	}

	if(chdir("../")<0)
	{
		printf("Change directory to '%s' failure: %s\n", TEST_DIR, strerror(errno));
		rv = -5;
		goto cleanup;
	}

	if((dirp=opendir(TEST_DIR))==NULL)
	{
		rv = -6;
		printf("Open directory %s error: %s\n", TEST_DIR, strerror(errno));
		goto cleanup;
	}

	while((direntp = readdir(dirp))!=NULL)
	{
		printf("Find file: %s\n", direntp->d_name);
	}

cleanup:
	if(fd1>=0)
	{
		close(fd1);
	}
	if(fd2>=0)
	{
		close(fd2);
	}
}
